﻿using Resources;
using Smatime.Web.Common;
using Smatime.Web.DAO;
using Smatime.Web.Models;
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Smatime.Web.Controllers
{
    public class LoginController : ApiController
    {

        // GET api/login/5
        [Route("api/login/{email}/{password}")]
        public UserAccess Get(string email, string password)
        {
            return new UserAccessRepository().Login(email, password);
        }

        // POST api/login
        public HttpResponseMessage Post([FromBody] UserAccess userAccess)
        {
            try
            {
                var result = new UserAccessRepository().Login(userAccess);
                return result != null
                    ? Request.CreateResponse(HttpStatusCode.OK, result)
                    : Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }

        [Route("api/resetpassword")]
        public HttpResponseMessage ResetPassword([FromBody] UserAccess userAccess)
        {
            try
            {
                var repository = new UserAccessRepository();
                var user = repository.GetByEmailAndResetCode(userAccess.Email, userAccess.ResetCode);
                // Check the existence of the reset code and email.
                if (user.IsNull() || user.ResetCodeCreatedTime == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, Texts.InvalidEmailAndResetCode);
                }
                // Check the validation of reset code.
                if (!(DateTime.Now.Subtract(user.ResetCodeCreatedTime.Value).TotalMinutes <= 60))
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, Texts.ResetCodeNotAlive);
                }
                // Update user password.
                if (!repository.ResetPassword(userAccess))
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, Texts.ResetPasswordFailed);
                }
                // Clear User access code in database.
                repository.UpdateResetCode(userAccess.Email, null, null);
                return Request.CreateResponse(HttpStatusCode.OK, Texts.ResetPasswordSuccessful);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }

        [Route("api/forgotpassword")]
        public HttpResponseMessage ForgotPassword([FromBody] UserAccess userAccess)
        {
            try
            {
                var repository = new UserAccessRepository();
                // Check the existence of email.
                var user = repository.GetByEmail(userAccess.Email);
                if (user.IsNull())
                {
                    return Request.CreateResponse(HttpStatusCode.NotFound, Texts.EmailNotExists);
                }
                // Create RESET CODE.
                var resetCode = RandomNumberHelper.GetRandomNumber();
                // Update reset code in Database with the current time.
                var isResetCodeCreated = repository.UpdateResetCode(userAccess.Email, resetCode, DateTime.Now);
                if (!isResetCodeCreated)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, Texts.CannotCreateAccessCode);
                }
                // Send email with the reset code
                var isSendEmailSuccessful = EmailHelper.GetInstance()
                    .SendForgotPasswordEmail(userAccess.Email, resetCode);
                return isSendEmailSuccessful
                    ? Request.CreateResponse(HttpStatusCode.OK, Texts.SendEmailSuccessfull)
                    : Request.CreateResponse(HttpStatusCode.BadRequest, Texts.CannotSendEmail);
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
            }
        }

        // POST api/login
        [Route("api/login/checkemail/")]
        public HttpResponseMessage CheckEmail([FromBody] UserAccess value)
        {
            try
            {
                var repos = new UserAccessRepository();
                var email = value.Email;
                var result = repos.CheckEmail(email);
                return Request.CreateResponse(HttpStatusCode.NotAcceptable, result);
            }
            catch (Exception)
            {
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }
    }
}